package com.zdb.n1.controller;

import com.zdb.n1.entity.ExerciseRecord;
import com.zdb.n1.entity.ExerciseType;
import com.zdb.n1.payload.response.MessageResponse;
import com.zdb.n1.service.ExerciseRecordService;
import com.zdb.n1.service.ExerciseTypeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/exercise-records")
public class ExerciseRecordController {

    @Autowired
    private ExerciseRecordService exerciseRecordService;
    
    @Autowired
    private ExerciseTypeService exerciseTypeService;

    @PostMapping
    public ResponseEntity<ExerciseRecord> createExerciseRecord(@Valid @RequestBody ExerciseRecord exerciseRecord) {
            ExerciseRecord saved = exerciseRecordService.saveExerciseRecord(exerciseRecord);
            return ResponseEntity.ok(saved);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ExerciseRecord> updateExerciseRecord(
            @PathVariable Long id, 
            @Valid @RequestBody ExerciseRecord exerciseRecord) {

        ExerciseRecord existingRecord = exerciseRecordService.getExerciseRecordById(id);
            exerciseRecord.setId(existingRecord.getId());
            ExerciseRecord updated = exerciseRecordService.saveExerciseRecord(exerciseRecord);
            return ResponseEntity.ok(updated);

    }

    @GetMapping("/{id}")
    public ResponseEntity<ExerciseRecord> getExerciseRecordById(@PathVariable Long id) {
            ExerciseRecord record = exerciseRecordService.getExerciseRecordById(id);
            // 确保日期格式正确
            if (record.getStartTime() != null) {
                Calendar calStart = Calendar.getInstance();
                calStart.setTime(record.getStartTime());
                calStart.set(Calendar.MILLISECOND, 0);
                record.setStartTime(calStart.getTime());
            }
            if (record.getEndTime() != null) {
                Calendar calEnd = Calendar.getInstance();
                calEnd.setTime(record.getEndTime());
                calEnd.set(Calendar.MILLISECOND, 0);
                record.setEndTime(calEnd.getTime());
            }
            return ResponseEntity.ok(record);

    }

    @GetMapping
    public ResponseEntity<List<ExerciseRecord>> getAllExerciseRecords() {
        return ResponseEntity.ok(exerciseRecordService.getAllExerciseRecordsForCurrentUser());
    }

    @GetMapping("/paged")
    public ResponseEntity<Page<ExerciseRecord>> getPagedExerciseRecords(Pageable pageable) {
        return ResponseEntity.ok(exerciseRecordService.getExerciseRecordsForCurrentUserPaged(pageable));
    }

    @GetMapping("/range")
    public ResponseEntity<List<ExerciseRecord>> getExerciseRecordsByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate) {
            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByDateRange(startDate, endDate);
            return ResponseEntity.ok(records);

    }

    @GetMapping("/by-type/{typeId}")
    public ResponseEntity<List<ExerciseRecord>> getExerciseRecordsByType(@PathVariable Long typeId) {
        ExerciseType exerciseType = exerciseTypeService.getExerciseTypeById(typeId);
        return ResponseEntity.ok(exerciseRecordService.getExerciseRecordsByType(exerciseType));
    }

    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getExerciseStats() {
        Map<String, Object> stats = new HashMap<>();
        
        stats.put("totalDuration", exerciseRecordService.getTotalDurationForCurrentUser());
        stats.put("totalCalories", exerciseRecordService.getTotalCaloriesForCurrentUser());
        
        Map<ExerciseType, Long> distribution = exerciseRecordService.getExerciseTypeDistributionForCurrentUser();
        Map<String, Long> simpleDistribution = new HashMap<>();
        distribution.forEach((type, count) -> simpleDistribution.put(type.getName(), count));
        stats.put("typeDistribution", simpleDistribution);
        
        return ResponseEntity.ok(stats);
    }

    @GetMapping("/stats/range")
    public ResponseEntity<Map<String, Object>> getExerciseStatsByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss", fallbackPatterns = {"yyyy-MM-dd'T'HH:mm:ss", "timestamp"}) Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss", fallbackPatterns = {"yyyy-MM-dd'T'HH:mm:ss", "timestamp"}) Date endDate) {
        Map<String, Object> stats = new HashMap<>();
        
        stats.put("totalDuration", exerciseRecordService.getTotalDurationForCurrentUserByDateRange(startDate, endDate));
        stats.put("totalCalories", exerciseRecordService.getTotalCaloriesForCurrentUserByDateRange(startDate, endDate));
        
        return ResponseEntity.ok(stats);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<MessageResponse> deleteExerciseRecord(@PathVariable Long id) {
        return ResponseEntity.ok(exerciseRecordService.deleteExerciseRecord(id));
    }
} 